/**
 * 
 */
package com.example.adapter;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * @author Rafael Holanda
 *
 */
public class DBAdapter {

	public static final String KEY_ROWID = "_id";
    public static final String KEY_LOGIN = "login";
    public static final String KEY_PASS = "pass";

	
	private static final String TAG = "DBAdapter";
	private static final String DATABASE_NAME = "MyDBAndroid";
	private static final int DATABASE_VERSION = 1;
	
	private static final String DATABASE_TABLE = "usuario";
	
	private static final String DATABASE_CREATE = 
			"create table usuario ("+ KEY_ROWID +" integer primary key autoincrement, "
	        + KEY_LOGIN + " text not null, " + KEY_PASS + " text not null);";

	
	private final Context context;
	
	private DataBaseHelper dbHelper;
	private SQLiteDatabase db;
	
	public DBAdapter(Context ctx) {
		this.context = ctx;
		dbHelper = new DataBaseHelper(context);
	}
	
	private static class DataBaseHelper extends SQLiteOpenHelper {

		public DataBaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			try {
				db.execSQL(DATABASE_CREATE);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS contacts");
            onCreate(db);
		}
		
	}
	
	public DBAdapter open() throws SQLException {
		db = dbHelper.getWritableDatabase();
		return this;
	}
	
	public void close() {
		dbHelper.close();
	}
	
	public long insertUsuario(String login, String pass) {
		ContentValues initialValues = new ContentValues();
		initialValues.put(KEY_LOGIN, login);
		initialValues.put(KEY_PASS, pass);
		return db.insert(DATABASE_TABLE, null, initialValues);
	}
	
	public boolean deleteUsuario(long rowId) {
		return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
	}
	
	public Cursor getAllUsuarios() {
		return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_LOGIN, KEY_PASS}, 
				null, null, null, null, null);
	}
	
	public Cursor getUsuario(String login) {
		Cursor mCursor = 
				db.query(true,DATABASE_TABLE, new String[] {KEY_ROWID, KEY_LOGIN, KEY_PASS}, 
						KEY_LOGIN + " = '" + login + "'", null,
		                null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		
		return mCursor;
	}
}
